package com.xinqi.common.third.oss.cloud;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.third.oss.OssProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * 阿里云 OSS服务
 *
 * @author linkai
 * @date 2023/2/18
 */
@Slf4j
public class AliYunOSSService extends OssService {
    private OSSClient client;
    private OssProperties.AliYun config;

    public AliYunOSSService(OssProperties config) {
        this.config = config.getAliYun();
        init();
    }

    private void init() {
        this.client = new OSSClient(config.getEndpoint(), config.getAccessKeyId(),
            config.getAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(byte[] data, String path, String contentType) {
        return upload(new ByteArrayInputStream(data), path, contentType);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        return upload(inputStream, path, null);
    }

    @Override
    public String upload(InputStream inputStream, String path, String contentType) {
        return upload(inputStream, path, null, contentType);
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String path, Map<String, String> header, String contentType) {
        try {
            PutObjectResult putObjectResult = client.putObject(config.getBucketName(), path, inputStream);
        } catch (Exception e) {
            log.error("上传文件失败，请检查配置信息", e);
            throw CommonErrors.BAD_REQUEST.asException("上传文件失败，请核对七牛配置信息");
        }
        return config.getDomain() + "/" + path;
    }
}
